from rest_framework.decorators import api_view
from rest_framework.request import Request
from rest_framework.response import Response

from api.serializers.product_serializer import ProductListResponseSerializer
from app.models import Product
from app.models.common_product import CommonProduct


@api_view(['GET'])
def get_common_products(request: Request):
    if request.user and not request.user.is_anonymous:  # 用户已登录
        products = Product.objects.raw("select * from app_product where id in (select app_productspec.product_id from app_productspec, app_orderproduct, app_order where  app_order.user_id=%d and app_order.id=app_orderproduct.order_id and app_orderproduct.spec_id=app_productspec.id order by app_order.created_datetime desc);" % request.user.id)
    else:
        queryset = CommonProduct.objects.filter(product__is_on_shell=True).order_by('prior')  # 按顺序排序
        products = [common_product.product for common_product in queryset]
    return Response(ProductListResponseSerializer(products, many=True).data)
